<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover" class="user-card">
          <div class="user-header">
            <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
              {{ userInfo?.username?.charAt(0)?.toUpperCase() }}
            </el-avatar>
            <h2>{{ userInfo?.username || '未登录' }}</h2>
            <div class="role-tag">
              <el-tag :type="getRoleTagType(userInfo?.role)">
                {{ getRoleName(userInfo?.role) }}
              </el-tag>
            </div>
          </div>
          <div class="user-info-list">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>账号: {{ userInfo?.username }}</span>
            </div>
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span>邮箱: {{ userInfo?.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <el-icon><Iphone /></el-icon>
              <span>手机: {{ userInfo?.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>注册时间: {{ formatDate(userInfo?.created_at) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本设置" name="basic">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>个人信息</span>
                </div>
              </template>
              
              <el-form 
                ref="formRef" 
                :model="form" 
                :rules="rules" 
                label-width="100px"
                label-position="left"
              >
                <el-form-item label="头像">
                  <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                  <div class="upload-tip">支持 jpg、png 格式，文件小于 2MB</div>
                </el-form-item>
                
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" />
                </el-form-item>
                
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" />
                </el-form-item>
                
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleSubmit" :loading="submitting">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="安全设置" name="security">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>修改密码</span>
                </div>
              </template>
              
              <el-form 
                ref="passwordFormRef" 
                :model="passwordForm" 
                :rules="passwordRules" 
                label-width="100px"
                label-position="left"
              >
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input 
                    v-model="passwordForm.oldPassword" 
                    type="password" 
                    show-password
                  />
                </el-form-item>
                
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="passwordForm.newPassword" 
                    type="password" 
                    show-password
                  />
                </el-form-item>
                
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password" 
                    show-password
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../store/user'
import { User, Message, Iphone, Calendar, Plus } from '@element-plus/icons-vue'
import request from '../../axios/request'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const activeTab = ref('basic')
const submitting = ref(false)
const changingPassword = ref(false)
const formRef = ref(null)
const passwordFormRef = ref(null)

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const avatarUrl = computed(() => userInfo.value?.avatar || defaultAvatar)

// 表单数据
const form = reactive({
  username: '',
  email: '',
  phone: '',
  avatar: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 角色选项
const roleOptions = {
  0: '超级管理员',
  1: '管理员',
  2: '主管',
  3: '员工',
  4: '老师'
}

// 获取角色名称
const getRoleName = (role) => roleOptions[role] || '未知角色'

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    0: 'danger',
    1: 'warning',
    2: 'success',
    3: 'info',
    4: 'primary'
  }
  return types[role] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 头像上传相关
const handleAvatarSuccess = (res, file) => {
  form.avatar = res.url
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleAvatarError = () => {
  // 头像加载失败时的处理
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 调用更新用户信息接口
    const res = await request.put('/admin/profile', form)
    
    // 更新本地用户信息
    userStore.setUserInfo({
      ...userInfo.value,
      ...form
    })
    
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    // 调用修改密码接口
    await request.put('/admin/password', passwordForm)
    
    ElMessage.success('密码修改成功，请重新登录')
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    
    // 退出登录
    setTimeout(() => {
      userStore.logout()
    }, 1500)
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请检查当前密码是否正确')
  } finally {
    changingPassword.value = false
  }
}

// 初始化表单数据
onMounted(() => {
  if (userInfo.value) {
    form.username = userInfo.value.username || ''
    form.email = userInfo.value.email || ''
    form.phone = userInfo.value.phone || ''
    form.avatar = userInfo.value.avatar || ''
  }
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  
  .user-card {
    height: 100%;
    
    .user-header {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px 0;
      border-bottom: 1px solid #eee;
      
      h2 {
        margin: 15px 0 5px;
        font-size: 18px;
      }
      
      .role-tag {
        margin-bottom: 10px;
      }
    }
    
    .user-info-list {
      padding: 20px 0;
      
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        .el-icon {
          margin-right: 10px;
          font-size: 18px;
          color: #409EFF;
        }
      }
    }
  }
  
  .card-header {
    font-weight: bold;
  }
  
  .avatar-uploader {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
    }
    
    .upload-tip {
      font-size: 12px;
      color: #606266;
      margin-top: 10px;
    }
  }
  
  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}
</style>